from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from StudyPlatform.models import PlayHistory


@login_required(login_url='login')
def history(request):
    if request.method == "POST":
        history_records = PlayHistory.objects.filter(user_id=request.user.id).all().order_by("-play_time")
        context = {
            "history_records": history_records,
        }
        return render(request, 'ajax/ajax_play_history.html', context)
    else:
        return render(request, 'play_history.html')


# 清除一条播放历史
@login_required(login_url='login')
def clearOneHistory(request):
    if request.method == "POST":
        courses_id = request.POST.get("courses_id")
        PlayHistory.objects.filter(courses_id=courses_id, user_id=request.user.id).delete()
        history_records = PlayHistory.objects.filter(user_id=request.user.id).all().order_by("-play_time")
        context = {
            "history_records": history_records,
        }
        return render(request, 'ajax/ajax_play_history.html', context)
    else:
        return redirect("history")


# 清空播放历史
@login_required(login_url='login')
def clearAll(request):
    if request.method == "POST":
        PlayHistory.objects.filter(user_id=request.user.id).delete()
        history_records = PlayHistory.objects.filter(user_id=request.user.id).all().order_by("-play_time")
        context = {
            "history_records": history_records,
        }
        return render(request, 'ajax/ajax_play_history.html', context)
    else:
        return redirect("history")
